<template>
	<view class="container-conversation">
		<u-navbar :is-back="false" title="社群">
			<view class="slot-wrap">
				<!-- <image src="@/static/IM/left-icon.png" style="width:20rpx;height:40rpx;margin-left:20rpx;"></image> -->
			</view>
			<view v-if="is_show" slot="right" class="right-icon" @click="goHaoy">
				<image src="@/static/IM/haoy.png" style="width:40rpx;height:40rpx;margin-right:20rpx;"></image>
			</view>
		</u-navbar>
		<template v-if="is_show">
			<view class="scroll-box">
				<view class="uni-list margintop-bar">
					<uni-swipe-action>
						<uni-swipe-action-item :threshold="0" :right-options="options2"
							@click="contentClick($event, item)" :key="item.conversationID"
							v-for="(item, index) in conversationList">
							<view class="itemli u-border-bottom" @tap="handleRoute(item.conversationID)">
								<!-- <TUI-conversation-item :data-type="item.type" :conversation="item"
								v-if="Object.keys(item).length > 0"></TUI-conversation-item> -->
								<view class="avatar-box">
									<image :src="item | setConversationAvatarHandler" mode=""></image>
									<view class="unread" v-if="item.unreadCount !== 0">
										<view class="read-text" v-if="item.unreadCount > 99">99+</view>
										<view class="read-text" v-else>{{ item.unreadCount }}</view>
									</view>
								</view>
								<view class="tui-conversation-lastMessage">
									<text class="text-ws">{{ item | getConversationName }}</text>
									<view class="" v-if="item.groupAtInfoList.length > 0">
										<text style="color: red;">[有人@我]</text>
									</view>
									<view class="text_er" v-else>
										<text v-if="item.lastMessage.isRevoked==true">[消息撤回通知]</text>
										<text v-else>{{ item.lastMessage.messageForShow }}</text>
									</view>
								</view>
								<view class="t-conversation-item-info">
									<text>{{ item | timeago }}</text>
									<!-- <view class="t-conversation-item-del">删除</view> -->
								</view>
							</view>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
				<view style="height:150rpx"></view>
			</view>
			<view class="bottom-back">
				<view class="bottom-area">
					<view v-if="showSelectTag" class="conversation-bubble" @tap.stop="handleEditToggle">
						<view v-for="(item, index) in array" :key="index" class="picker" :data-name="item.name"
							@tap="handleOnTap">{{ item.name }}</view>
					</view>
					<image @tap="showMore" class="btn-show-more" src="/static/static/assets/add.svg"></image>
					<!-- <view @tap="learnMore" class="im-link">了解更多IM功能</view> -->
				</view>
			</view>
		</template>
		<view style="margin-top: 10vh;" v-else>
			<u-empty text="列表为空" mode="list"></u-empty>
		</view>
	</view>
</template>
<!-- 这里有个加载的补丁逻辑待优化，页面向SDK请求conversationList的时候会有时延，
造成页面的一个抖动，这里加一个if逻辑打一个补丁，后续继续优化 -->
<script>
	import {
		setTokenStorage
	} from '@/utils/token';
	import logger from '@/utils/logger';
	import {
		genTestUserSig
	} from '@/debug/GenerateTestUserSig.js';
	const {
		getTokenStorage
	} = require('@/utils/token.js');
	import {
		getUserinfo
	} from '@/network/loginAndMy.js'
	import {
		config,
	} from '@/network/api.js'
	import {
		caculateTimeago
	} from '@/components/base/common.js';
	const app = getApp();
	import TUIConversationItem from '@/components/tui-conversation/conversation-item/index';
	import TUIMessageList from '@/components/tui-chat/message-list/index';

	export default {
		data() {
			return {
				applyStatus: '',
				userID: '',
				conversationList: [],
				showSelectTag: false,
				is_show: false,
				array: [{
						name: '发起群聊'
					},
					{
						name: '加入群聊'
					},
					{
						name: '查看群列表'
					}
				],
				info: {},
				conversItem: {},
				options2: [
					// {
					// 	text: '免打扰',
					// 	style: {
					// 		fontSize: '25rpx',
					// 		backgroundColor: '#007aff'
					// 	}
					// },
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				],
			};
		},

		components: {
			TUIConversationItem,
			TUIMessageList
		},
		props: {},
		/**
		 * 生命周期函数--监听页面加载
		 */
		filters: {
			setConversationAvatarHandler(conversation) {
				if (conversation.type === '@TIM#SYSTEM') {
					return 'https://web.sdk.qcloud.com/component/TUIKit/assets/system.png';
				}

				if (conversation.type === 'C2C') {
					return conversation.userProfile.avatar ||
						'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png';
				}

				if (conversation.type === 'GROUP') {
					return conversation.groupProfile.avatar || '/static/static/assets/gruopavatar.svg';
				}
			},
			getConversationName(conversation) {
				if (conversation.type === '@TIM#SYSTEM') {
					return '系统通知';
				}

				if (conversation.type === 'C2C') {
					return conversation.remark || conversation.userProfile.nick || conversation.userProfile.userID;
				}

				if (conversation.type === 'GROUP') {
					return conversation.groupProfile.name || conversation.groupProfile.groupID;
				}
			},
			timeago(item) {
				if (caculateTimeago(item.lastMessage.lastTime * 1000) == '1970-01-01') {
					return '最近'
				} else {
					return caculateTimeago(item.lastMessage.lastTime * 1000)
				}
			}
		},
		onLoad() {
			this.configRe()
			let token = uni.getStorageSync("token1")
			console.log(token, 'token')
			if (token != '') {
				this.getUserinfoRe()
				this.login()
			} else {
				uni.reLaunch({
					url: '/pages/subpackage/landing_operation/logIn'
				})
			}
		},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			uni.$TUIKit.off(uni.$TUIKitEvent.SDK_READY, this.onConversationListUpdated);
		},
		onShow() {
			this.getUserinfoRe()
			// this.getConversationList()
		},
		methods: {
			contentClick(e, item) {
				this.conversItem = item
				if (e.content.text == '免打扰') {
					uni.showToast({
						title: '免打扰',
						icon: 'none'
					});
					this.disturb()
				} else {
					uni.showToast({
						title: '删除',
						icon: 'none'
					});
					this.deleteConversation()
				}
			},
			// 免打扰
			disturb() {
				uni.$TUIKit.setMessageRemindType({
					groupID: this.conversItem.groupProfile.groupID,
					messageRemindType: uni.$TUIKitTIM.TYPES.MSG_REMIND_ACPT_NOT_NOTE
				}).then(imResponse => {
					uni.showToast({
						title: "已设置为免打扰",
						icon: "none",
						duration: 2000,
					});
					// this.$u.toast(imResponse.message);
					console.log(imResponse, '免打扰成功')
				}).catch(err => {
					console.log(err, '免打扰失败')
					// this.$u.toast(err.message);
				})
			},
			// 删除会话
			deleteConversation() {
				uni.showModal({
					content: '确认删除会话？',
					success: res => {
						if (res.confirm) {
							uni.$TUIKit.deleteConversation(this.conversItem.conversationID);
							this.setData({
								conversation: {},
								xScale: 0
							});
						}
					}
				});
			},
			// 获取配置信息
			configRe() {
				config().then(res => {
					this.applyStatus = res.data.applyStatus
				})
			},
			gengx() {
				uni.$TUIKit.updateMyProfile({
						nick: this.info.nickname,
						avatar: this.info.avatar,
						gender: uni.$TUIKitTIM.TYPES.GENDER_MALE,
						selfSignature: '我的个性签名',
						allowType: uni.$TUIKitTIM.TYPES.ALLOW_TYPE_ALLOW_ANY
					}).then(imResponse => {})
					.catch(err => {})
			},
			// 获取用户信息
			getUserinfoRe() {
				getUserinfo().then(res => {
					if (res.code == 1) {
						this.info = res.data
						this.userID = res.data.ownid + ''
						this.login()
						console.log(this.userID, 'user_id')
					}
				})
			},
			login() {
				const userID = this.userID;
				const userSig = genTestUserSig(userID).userSig;
				const SDKAppID = app.globalData.SDKAppID;
				logger.log(`TUI-login | login  | userSig:${userSig} userID:${userID}`);
				// #ifdef  APP-PLUS
				uni.$aegis.reportEvent({
					name: 'platform',
					ext1: 'platform-APP',
					ext2: 'uniTuikitExternal',
					ext3: `${SDKAppID}`,
				})
				// #endif
				// #ifdef MP-WEIXIN  
				uni.$aegis.reportEvent({
					name: 'platform',
					ext1: 'platform-MP-WEIXIN',
					ext2: 'uniTuikitExternal',
					ext3: `${SDKAppID}`,
				})
				// #endif
				// #ifdef H5
				uni.$aegis.reportEvent({
					name: 'platform',
					ext1: 'platform-H5',
					ext2: 'uniTuikitExternal',
					ext3: `${SDKAppID}`,
				})
				uni.showToast({
					title: 'TUIKit 暂不支持 H5 / web ，请使用者自己完成兼容哦～ ',
					icon: 'none',
					duration: 3000
				});
				// #endif
				app.globalData.userInfo = {
					userSig,
					userID
				};
				setTokenStorage({
					userInfo: app.globalData.userInfo
				});
				wx.setStorageSync(`TIM_${getApp().SDKAppID}_isTUIKit`, true);
				uni.$TUIKit.login({
					userID: userID,
					userSig: userSig
				}).then(() => {
					this.is_show = true
					uni.$aegis.reportEvent({
						name: 'login',
						ext1: 'login-success',
						ext2: 'uniTuikitExternal',
						ext3: `${SDKAppID}`,
					})
				}).catch((error) => {
					this.is_show = false
					console.log('触发')
					uni.$aegis.reportEvent({
						name: 'login',
						ext1: `login-failed#error:${error}`,
						ext2: 'uniTuikitExternal',
						ext3: `${SDKAppID}`,
					})
				})



				// 登录原生插件
				// #ifdef APP-PLUS
				if (typeof(uni.$TUICalling) == 'undefined') {
					// uni.showToast({
					// 	title: '如果需要音视频功能，请集成插件使用真机运行并且自定义基座调试哦～',
					// 	icon: 'none',
					// 	duration: 3000
					// });
					// logger.error(
					// 	'请使用真机运行并且自定义基座调试，否则影响音视频功能～ 插件地址：https://ext.dcloud.net.cn/plugin?id=7097 , 调试地址：https://nativesupport.dcloud.net.cn/NativePlugin/use/use'
					// 	);
				} else {
					uni.$TUICalling.login({
							sdkAppID: SDKAppID,
							userID: userID,
							userSig: userSig
						},
						res => {
							console.log(JSON.stringify(res.msg));
							uni.showToast({
								title: 'login',
								icon: 'none'
							});
						}
					);
				}

				// #endif
				// uni.showToast({
				// 	title: "登陆成功",
				// 	icon: "none",
				// 	duration: 2000,
				// });
				// 登入后拉去会话列表
				this.getConversationList();
				uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);

				this.gengx()
				// if (this.path && this.path !== 'undefined') {
				// 	uni.redirectTo({
				// 		url: this.path
				// 	});
				// } else {
				// 	uni.switchTab({
				// 		url: '../TUI-Index/index'
				// 	});
				// }
			},
			handleRoute(id) {
				const url = `/pages/subpackage/IM/TUI-Chat/chat?conversationID=${id}`;
				uni.navigateTo({
					url
				});
			},
			onConversationListUpdated(event) {
				logger.log('TUI-conversation | onConversationListUpdated  |ok');
				this.setData({
					conversationList: event.data
				});
				console.log(this.conversationList, '发接口的那个空间实在不耐烦卡上')
				// uni.$TUIKit.getGroupList().then(imResponse => {
				// 	console.log(imResponse, '列表')
				// })
			},

			getConversationList() {
				uni.$TUIKit.getConversationList().then(imResponse => {
					logger.log(
						`TUI-conversation | getConversationList | getConversationList-length: ${imResponse.data.conversationList.length}`
					);
					this.setData({
						conversationList: imResponse.data.conversationList
					});
					console.log(this.conversationList, '回话列表')
				});
			},

			showMore() {
				this.setData({
					showSelectTag: !this.showSelectTag
				});
			},

			learnMore() {
				uni.navigateTo({
					url: '../../TUI-User-Center/webview/webview?url=https://cloud.tencent.com/product/im'
				});
			},

			handleOnTap(event) {
				this.setData({
						showSelectTag: false
					},
					() => {
						switch (event.currentTarget.dataset.name) {
							case '发起群聊':
								this.$createGroup();
								break;
							case '加入群聊':
								this.$joinGroup();
								break;
							case '查看群列表':
								this.$searchGroup();
								break;
							default:
								break;
						}
					}
				);
			},

			goHomePage() {
				// uni.navigateTo 不能跳转到 tabbar 页面，使用 uni.switchTab 代替
				uni.switchTab({
					url: '../../TUI-Index/index'
				});
			},

			handleEditToggle() {
				this.setData({
					showSelectTag: false
				});
			},

			$createConversation() {
				uni.navigateTo({
					url: '../create-conversation/create'
				});
			},

			$createGroup() {
				uni.navigateTo({
					url: '/pages/subpackage/IM/TUI-Group/create-group/create'
				});
			},

			$joinGroup() {
				uni.navigateTo({
					url: '/pages/subpackage/IM/TUI-Group/join-group/join'
				});
			},
			$searchGroup() {
				console.log('触发')
				uni.navigateTo({
					url: '/pages/subpackage/IM/qun/qun'
				})
			},
			goHaoy() {
				uni.navigateTo({
					url: '/pages/subpackage/IM/haoy/haoy'
				})
			}
		}
	};
</script>
<style scoped lang="scss">
	@import './group.css';

	.itemli:active {
		background-color: #e5e5e5;
	}

	.itemli {
		display: flex;
		align-items: center;
		height: 150rpx;
		padding: 0 60rpx;
		border-bottom: 1rpx solid #e5e5e5;

		.avatar-box {
			position: relative;

			>image {
				width: 100rpx;
				height: 100rpx;
				border-radius: 20rpx;
			}

			.unread {
				position: absolute;
				top: -10rpx;
				right: -10rpx;
				padding: 0 10rpx;
				height: 15px;
				border-radius: 16rpx;
				color: #ffffff;
				background-color: red;
			}

			.read-text {
				line-height: 15px;
				font-size: 10px;
			}
		}

		.tui-conversation-lastMessage {
			width: 350rpx;
			margin-left: 40rpx;

			.text_er {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}

		.t-conversation-item-info {
			margin-left: auto;
		}
	}

	.container-conversation {
		.content-box {
			flex: 1;
			/* #ifdef APP-NVUE */
			justify-content: center;
			/* #endif */
			height: 44px;
			line-height: 44px;
			padding: 0 15px;
			position: relative;
			background-color: #fff;
			border-bottom-color: #f5f5f5;
			border-bottom-width: 1px;
			border-bottom-style: solid;
		}

		.content-text {
			font-size: 15px;
		}

		.example-body {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
			justify-content: center;
			padding: 10px 0;
			background-color: #fff;
		}

		.button {
			border-color: #e5e5e5;
			border-style: solid;
			border-width: 1px;
			padding: 4px 8px;
			border-radius: 4px;
		}

		.button-text {
			font-size: 15px;
		}

		.slot-button {
			/* #ifndef APP-NVUE */
			display: flex;
			height: 100%;
			/* #endif */
			flex: 1;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			padding: 0 20px;
			background-color: #ff5a5f;
		}

		.slot-button-text {
			color: #ffffff;
			font-size: 14px;
		}
	}
</style>